package com.jar.exercise.java8新特性.StreamAPI;


import com.jar.exercise.java8新特性.方法的引用.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Steam API的终止操作
 * <p>
 * 匹配与查找
 * <p>
 * 规约
 * <p>
 * 收集
 */


public class TestStreamAPI3 {
/**
 * 匹配与查找
 */

    @Test
    public void test1() {
        List<Employee> student = Employee.getStudent();
//        boolean allMatch(Predicate<? super T> predicate);
        boolean b = student.stream().allMatch(e -> e.getAge() > 10);
//        Stream<T> filter(Predicate<? super T> predicate);
    }

/**
 * 规约
 */

    @Test
    public void test2() {
        //   reduce 将流种的元素反复结合，得到一个值
        //计算1-10的自然之和
        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        Integer reduce = integers.stream().reduce(0, Integer::sum);
        System.out.println(reduce);

        //计算员工种的年龄之和
        List<Employee> student = Employee.getStudent();
        Stream<Integer> age = student.stream().map(Employee::getAge);
        Optional<Integer> reduce1 = age.reduce((a1, a2) -> a1 + a2);
        System.out.println(reduce1);
    }

/**
 * 收集
 */


/*过滤、收集*/

    @Test
    public void test3() {
        List<Employee> student = Employee.getStudent();
        List<Employee> s = student.stream().filter(e -> e.getName().contains("张")).collect(Collectors.toList());
        System.out.println(s);
    }

	/*分组*/

    @Test
    public void test4() {
        List<Employee> student = Employee.getStudent();
        Map<String, List<Employee>> collect = student.stream().collect(Collectors.groupingBy(Employee::getSex));
        System.out.println(collect);
    }

	/*List-->Map,(a,b)->a ：如果key冲突就不做添加，(a,b)->b：覆盖*/

    @Test
    public void test5() {
        List<Employee> emp = Employee.getStudent();
        Map<String, Employee> collect = emp.stream().collect(Collectors.toMap(Employee::getName, employee -> employee,(a,b)->a));
        System.out.println(collect);
    }
}

